package gee

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// H 个人理解是为了构造json的时候稍微简洁一点
type H map[string]interface{}

// Context 对handle请求的参数做了封装，存了w，req，等相关内容
type Context struct {
	Writer	http.ResponseWriter
	Req		*http.Request
	Path	string
	Method	string
	Params	map[string]string
	StatusCode	int
}

// NewContext 创建一个Context，相关参数来源见代码
func NewContext(w http.ResponseWriter, req *http.Request) *Context {
	return &Context{
		Writer: w,
		Req: req,
		Path: req.URL.Path,
		Method: req.Method,
	}
}

// PostForm post请求表单的data相关参数的查询
func (c *Context) PostForm(key string) string {
	return c.Req.FormValue(key)
}

// Query get请求的params相关参数查询
func (c *Context) Query(key string) string {
	return c.Req.URL.Query().Get(key)
}

// Status 状态码设置
func (c *Context) Status(code int) {
	c.StatusCode = code
	c.Writer.WriteHeader(code)
}

// setHeader 响应头的k-v设置
func (c *Context) setHeader(key string, value string) {
	c.Writer.Header().Set(key, value)
}

// String 写入string类型的response
func (c *Context) String(code int, format string, values ...interface{}) {
	c.setHeader("Content-Type", "text/plain")
	c.Status(code)
	c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}

// JSON 写入json类型的response
func (c *Context) JSON(code int, obj interface{}) {
	c.setHeader("Content-Type", "application/json")
	c.Status(code)
	encoder := json.NewEncoder(c.Writer)
	if err := encoder.Encode(obj); err != nil {
		http.Error(c.Writer, err.Error(), 500)
	}
}

// Data 直接写入data字节码的response
func (c *Context) Data(code int, data []byte) {
	c.Status(code)
	c.Writer.Write(data)
}

// HTML 写入html类型的返回值
func (c *Context) HTML(code int, html string) {
	c.setHeader("Content-Type", "text/html")
	c.Status(code)
	c.Writer.Write([]byte(html))
}

// Param 拿到动态路由中的相关数据值
func (c *Context) Param(key string) string {
	value, _ := c.Params[key]
	return value
}